package com.sskj.postar.service.impl;

import com.sskj.postar.core.config.ServiceException;
import com.sskj.postar.core.universal.AbstractService;
import com.sskj.postar.mapper.FabiPublishMapper;
import com.sskj.postar.enums.SysConfigEnum;
import com.sskj.postar.model.FabiPublish;
import com.sskj.postar.model.SystemConfig;
import com.sskj.postar.service.FabiPublishService;
import com.sskj.postar.service.SystemConfigService;
import com.sskj.postar.service.UserAssetService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 *
 * @Description: FabiPublishService接口实现类
 * @date 2018/11/12 17:15
 */
@Service
public class FabiPublishServiceImpl extends AbstractService<FabiPublish> implements FabiPublishService {

    @Resource
    private FabiPublishMapper fabiPublishMapper;
    @Resource
    UserAssetService userAssetService;
    @Resource
    SystemConfigService systemConfigService;

    @Override
    public List<Map> selectMarketByType(FabiPublish f) {

        return fabiPublishMapper.selectMarketByType(f);
    }

    @Transactional(rollbackFor = {})
    @Override
    public void publish(FabiPublish fabiPublish) {
        Integer insert = insert(fabiPublish);
        if (insert < 0) {
            throw new ServiceException("发布订单失败");
        }
        if (fabiPublish.getType() == 2) {//出售
            SystemConfig systemConfig = systemConfigService.selectOne(systemConfigService.selectOne(SysConfigEnum.FABI_FEE.systemConfig));
            BigDecimal allMoneyBig = new BigDecimal(fabiPublish.getPublishNum());
            BigDecimal feeBig = allMoneyBig.multiply(new BigDecimal(systemConfig.getValue()));
            userAssetService.updateMoney(fabiPublish.getUserId(), "-" + allMoneyBig.add(feeBig).toPlainString(), allMoneyBig.add(feeBig).toPlainString());
        }
    }

    @Override
    public void updateLeftNum(Integer id, String addNum) {
        if (fabiPublishMapper.updateLeftNum(id,addNum)<0){
            throw new ServiceException("订单交易失败");
        }
    }
}

